<script lang="ts">
import {defineComponent, onMounted, reactive, toRefs,} from 'vue'
import {PageParam, type QueryParamConfig, TableListConfig} from "@/components/pageTable/types/type.ts";
import {axiosHttp} from "@/util/axios.ts";
import {CompUserError} from "@/common/comTypes/errorType.ts";

//通用分页展示组件 适用于普通的条件查询以及分页展示
export default defineComponent({
  name: 'pageTable',

  emits: ['sizeChange', 'currentPageChange', 'search', 'handleChangeItem', 'handlerAdd'],
  props: {
    queryConfigList: {
      type: Array<QueryParamConfig>,
      default: () => []
    },
    tableConfigList: {
      type: Array<TableListConfig>,
      default: () => []
    },
    defaultPageParam: {
      type: PageParam,
      default: () => {
        return new PageParam()
      }
    },
    queryParam: {
      type: Object,
      default: () => {
      }
    },
    //每行条件字段数
    rowNumber: {
      type: Number,
      default: 3
    },
    //自动查询 内部查询
    autoSearch: {
      type: Boolean,
      default: true,
    },
    //url 内部查询url
    listUrl: {
      type: String,
      default: ""
    },
    //外部查询结果
    tableData: {
      type: Array,
      default: () => []
    },
    total: {
      type: Number,
      default: 0
    },

    pageSizes: {
      type: Array,
      default: () => [
        5, 10, 15, 20, 25
      ]
    },
    openSelection: {
      type: Boolean,
      default: true
    },
    changeItemTitle: {
      type: String,
      default: "勾选的数据"
    },
    showButton: {
      type: Boolean,
      default: true
    },
    openAdd: {
      type: Boolean,
      default: true
    },
    addTitle: {
      type: String,
      default: "添加"
    },
    emptyText: {
      type: String,
      default: "暂无数据"
    },
    rowKey: {
      type: String,
      default: "id"
    },
    treeProps: {
      type: Object,
      default: {
        hasChildren: 'hasChildren',
        children: 'children',
        checkStrictly: false
      }
    }


  },
  setup(props, {emit}) {

    onMounted(() => {
      data.queryParam = props.queryParam
      if (props.autoSearch) {
        if(!props.listUrl){
          throw new CompUserError("组件使用错误:开启自动查询必须填写查询地址")
        }
        methods.init()
      }
      staticData.initQueryParam = {...props.queryParam}
    })

    const data = reactive({
      innerTableData: <any>[],
      pageParam: new PageParam(),
      innerTotal: 0,
      queryParam: {},
      changeItems: <object>[],
      loading: false,

    })

    const staticData = {
      initQueryParam: {}
    }
    const methods = {
      async init() {
        data.loading = true
        const res = await axiosHttp.post(props.listUrl, data.pageParam.buildParam(props.queryParam))
        data.loading = false
        if (res.isSuccess()) {
          data.innerTotal = res.data?.total
          data.innerTableData = res.data?.list
        }

      },
      handleSizeChange(size: number) {

        if (props.autoSearch) {
          methods.init()
        } else {
          emit('sizeChange', data.pageParam)
        }
      },
      handleCurrentChange(current: number) {
        if (props.autoSearch) {
          methods.init()
        } else {
          emit('currentPageChange', data.pageParam)
        }
      },
      reset() {
        console.log(staticData.initQueryParam)
        data.queryParam = {...staticData.initQueryParam}

      },
      search() {
        if (props.autoSearch) {
          methods.init();
        } else {
          emit("search", data.queryParam)
        }
      },
      changeItem(arr: Array<object>) {
        data.changeItems = arr
      },
      handleChangeItem() {
        emit("handleChangeItem", data.changeItems)
      },
      //添加
      handlerAdd() {
        emit("handlerAdd")
      }
    }

    const validators = {}


    const rules = reactive({})

    const refs = {}


    return {
      ...toRefs(data),
      ...methods,
      validators,
      rules,
      ...refs,
      ...toRefs(staticData)
    }
  }
})
</script>

<template>
  <div style="display: flex;flex-direction: column;gap: 8px">
    <!--    button-->
    <div>
      <el-row v-if="showButton">
        <slot name="customButtonsSlot">
          <el-button v-if="openAdd" type="text" @click="handlerAdd">{{ addTitle }}</el-button>
          <el-button v-if="openSelection" type="text" @click="handleChangeItem">{{ changeItemTitle }}</el-button>
        </slot>

      </el-row>
    </div>
    <!--    query-->
    <div v-if="queryConfigList.length>0" style="display: flex;align-items: center">
      <el-col :span="20">
        <el-row style="width: 80%" v-for="(row,rowIndex) in Math.ceil(queryConfigList.length/rowNumber)">
          <el-col
              v-for="(col,colIndex) in (rowIndex<Math.ceil(queryConfigList.length/rowNumber)-1?rowNumber:(queryConfigList.length%rowNumber==0?rowNumber:queryConfigList.length%rowNumber))"
              :span="Math.floor(24/rowNumber)">
            <el-form-item :prop="queryConfigList[rowIndex*rowNumber+colIndex]?.prop"
                          :label="queryConfigList[rowIndex*rowNumber+colIndex]?.label"
                          label-width="auto"
                          :style="{
                width:queryConfigList[rowIndex*rowNumber+colIndex]?.width||'90%'
              }"
            >
              <el-input
                  v-if="!queryConfigList[rowIndex*rowNumber+colIndex]?.customSlotName"
                  v-model="queryParam[queryConfigList[rowIndex*rowNumber+colIndex]?.prop]"
                  :placeholder="queryConfigList[rowIndex*rowNumber+colIndex]?.placeholder?queryConfigList[rowIndex*rowNumber+colIndex]:'请输入'+queryConfigList[rowIndex*rowNumber+colIndex]?.label"
              >

              </el-input>
              <slot v-else :name="queryConfigList[rowIndex*rowNumber+colIndex]?.customSlotName">
              </slot>

            </el-form-item>


          </el-col>

        </el-row>
      </el-col>
      <el-col :span="4">
        <div style="display: flex;justify-content: center;align-items: center;gap:8px;">
          <el-button @click="reset">重置</el-button>
          <el-button @click="search">查询</el-button>
        </div>
      </el-col>

    </div>
    <!--    table list-->
    <div>
      <el-table v-loading="loading"
                :empty-text="emptyText"
                :row-key="rowKey"
                :tree-props="treeProps"
                :data="autoSearch?innerTableData:tableData"
                @selection-change="changeItem">
        <el-table-column v-if="openSelection" type="selection" align="center" width="55"/>
        <el-table-column
            :label="item.label"
            :prop="item.prop"
            :width="item.width"
            :min-width="item.minWidth"
            :key="item.prop"
            align="center"
            v-for="(item,index) in tableConfigList">
          <template #default="{row,$index}">

            <slot v-if="item.customSlotName" :row="row" :index="$index" :name="item.customSlotName">

            </slot>
            <div v-else>
              {{ row[item.prop] || "-" }}
            </div>
          </template>

        </el-table-column>
      </el-table>
      <!--      分页 -->
      <el-pagination
          v-model:current-page="pageParam.current"
          v-model:page-size="pageParam.size"
          :page-sizes="pageSizes"

          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
      />
    </div>

  </div>

</template>

<style scoped>

</style>